package com.jack.helloworld.activity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.jack.helloworld.R;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import androidx.appcompat.app.AppCompatActivity;

public class FileActivity extends AppCompatActivity implements View.OnClickListener {

    EditText etWriteFile;
    Button btnWriteFile;
    TextView tvReadFile;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_file);

        initView();
        initData();
    }

    private void initView() {
        etWriteFile = (EditText) findViewById(R.id.etWriteFile);
        btnWriteFile = (Button) findViewById(R.id.btnWriteFile);
        tvReadFile = (TextView) findViewById(R.id.tvReadFile);

    }

    private void initData() {
        File file = this.getFilesDir();
        Log.d("jack", "getFilesDir:" + file);
        file = this.getCacheDir();
        Log.d("jack", "getCacheDir:" + file);
        file = this.getDir("jack", MODE_PRIVATE);
        Log.d("jack", "getDir:" + file);
        file = this.getExternalFilesDir("jack");
        Log.d("jack", "getExternalFilesDir:" + file);
        file = this.getExternalCacheDir();
        Log.d("jack", "getExternalCacheDir:" + file);


        btnWriteFile.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        writeFile(etWriteFile.getText().toString());
        tvReadFile.setText(readFile());
    }

    private void writeFile(String content) {
        FileOutputStream fos = null;
        try {
            fos = openFileOutput("1.txt", MODE_PRIVATE);
            fos.write(content.getBytes());
            fos.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private String readFile() {
        String content = null;
        try {
            FileInputStream fis = openFileInput("1.txt");
            byte[] buffer = new byte[1024];
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int len = 0;
            while ((len = fis.read(buffer)) != -1) {
                baos.write(buffer);
            }

            content = baos.toString();
            Log.d("jack", "content:" + content);

            baos.close();
            fis.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return content;
    }


}
